<template>
    <div>
        <div class="gva-search-box">
            <el-form
                ref="elSearchFormRef"
                :inline="true"
                :model="searchInfo"
                class="demo-form-inline"
                :rules="searchRule"
                @keyup.enter="onSubmit"
            >
                <el-form-item label="创建日期" prop="createdAt">
                    <template #label>
                        <span>
                            创建日期
                            <el-tooltip
                                content="搜索范围是开始日期（包含）至结束日期（不包含）"
                            >
                                <el-icon><QuestionFilled /></el-icon>
                            </el-tooltip>
                        </span>
                    </template>
                    <el-date-picker
                        v-model="searchInfo.startCreatedAt"
                        type="datetime"
                        placeholder="开始日期"
                        :disabled-date="
                            (time) =>
                                searchInfo.endCreatedAt
                                    ? time.getTime() >
                                      searchInfo.endCreatedAt.getTime()
                                    : false
                        "
                    ></el-date-picker>
                    —
                    <el-date-picker
                        v-model="searchInfo.endCreatedAt"
                        type="datetime"
                        placeholder="结束日期"
                        :disabled-date="
                            (time) =>
                                searchInfo.startCreatedAt
                                    ? time.getTime() <
                                      searchInfo.startCreatedAt.getTime()
                                    : false
                        "
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="客户编号" prop="customerNum">
                    <el-input v-model="searchInfo.customerNum"  placeholder="请输入客户编号" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit"
                        >查询</el-button
                    >
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box">
            <div class="role">
                <LTable
                    :columns="columns"
                    :tableData="tableData"
                    :pages="pages"
                    @updateMultipleSelection="handleSelectionChange"
                    @changePages="changePages"
                >
                    <template #action>
                        <div class="gva-btn-list">
                            <el-button
                                type="primary"
                                icon="plus"
                                @click="openCreateAndEdit"
                                >新增</el-button
                            >
                            <el-button
                                icon="delete"
                                style="margin-left: 10px"
                                :disabled="!multipleSelection.length"
                                @click="onDelete"
                                >删除</el-button
                            >
                        </div>
                    </template>
                    <template #event>
                        <el-table-column
                            align="left"
                            label="操作"
                            fixed="right"
                            min-width="240"
                            width="240"
                        >
                            <template #default="scope">
                                <el-button
                                    type="primary"
                                    link
                                    icon="edit"
                                    class="table-button"
                                    @click="updateCustomerInfoFunc(scope.row)"
                                    >变更</el-button
                                >
                                <el-button
                                    type="primary"
                                    link
                                    icon="delete"
                                    @click="deleteRow(scope.row)"
                                    >删除</el-button
                                >
                            </template>
                        </el-table-column>
                    </template>
                </LTable>
            </div>
        </div>
    </div>
</template>

<script setup>
import {
    createCustomerInfo,
    deleteCustomerInfo,
    deleteCustomerInfoByIds,
    updateCustomerInfo,
    findCustomerInfo,
    getCustomerInfoList,
} from "@/api/confCustomerInfo";

// 全量引入格式化工具 请按需保留
import {
    getDictFunc,
    formatDate,
    formatBoolean,
    filterDict,
    ReturnArrImg,
    onDownloadFile,
} from "@/utils/format";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
// 引入组件
import LTable from "@/components/LTable/LTable.vue";
import searchForm from "@/components/searchForm/searchForm.vue";

defineOptions({
    name: "CustomerInfo",
});

const router = useRouter();

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
    customerNum: "",
});

// 验证规则
const rule = reactive({});

const searchRule = reactive({
    createdAt: [
        {
            validator: (rule, value, callback) => {
                if (
                    searchInfo.value.startCreatedAt &&
                    !searchInfo.value.endCreatedAt
                ) {
                    callback(new Error("请填写结束日期"));
                } else if (
                    !searchInfo.value.startCreatedAt &&
                    searchInfo.value.endCreatedAt
                ) {
                    callback(new Error("请填写开始日期"));
                } else if (
                    searchInfo.value.startCreatedAt &&
                    searchInfo.value.endCreatedAt &&
                    (searchInfo.value.startCreatedAt.getTime() ===
                        searchInfo.value.endCreatedAt.getTime() ||
                        searchInfo.value.startCreatedAt.getTime() >
                            searchInfo.value.endCreatedAt.getTime())
                ) {
                    callback(new Error("开始日期应当早于结束日期"));
                } else {
                    callback();
                }
            },
            trigger: "change",
        },
    ],
});

const elFormRef = ref();
const elSearchFormRef = ref();

// =========== 表格控制部分 ===========
const pages = ref({
    page: 1,
    pageSize: 10,
    total: 0,
});
const tableData = ref([]);
const searchInfo = ref({});
// ======表格头部数据======
const columns = ref([
    {
        prop: "customerNum",
        width: 200,
        label: "客户编号",
        show: true,
    },
    {
        prop: "CreatedAt",
        width: 200,
        label: "创建日期",
        show: true,
    },
    {
        prop: "CreatedPeo",
        width: 200,
        label: "创建人",
        show: true,
    },
    {
        prop: "UpdatedAt",
        width: 200,
        label: "更新时间",
        show: true,
    },
]);

// 重置
const onReset = () => {
    searchInfo.value = {};
    getTableData();
};

// 搜索
const onSubmit = () => {
    elSearchFormRef.value?.validate(async (valid) => {
        if (!valid) return;
        pages.value.page = 1;
        pages.value.pageSize = 10;
        getTableData();
    });
};

// 改变页码
const changePages = (currentPages) => {
    pages.value = {
        ...pages.value,
        ...currentPages,
    };
    getTableData();
};

// 查询
const getTableData = async () => {
    const table = await getCustomerInfoList({
        page: pages.value.page,
        pageSize: pages.value.pageSize,
        ...searchInfo.value,
    });
    if (table.code === 0) {
        tableData.value = table.data.list;
        pages.value.total = table.data.total;
        pages.value.page = table.data.page;
        pages.value.pageSize = table.data.pageSize;
    }
};

getTableData();

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {};

// 获取需要的字典 可能为空 按需保留
setOptions();

// 多选数据
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        deleteCustomerInfoFunc(row);
    });
};

// 多选删除
const onDelete = async () => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        const IDs = [];
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: "warning",
                message: "请选择要删除的数据",
            });
            return;
        }
        multipleSelection.value &&
            multipleSelection.value.map((item) => {
                IDs.push(item.ID);
            });
        const res = await deleteCustomerInfoByIds({ IDs });
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "删除成功",
            });
            if (tableData.value.length === IDs.length && pages.value.page > 1) {
                pages.value.page--;
            }
            getTableData();
        }
    });
};

// 行为控制标记（弹窗内部需要增还是改）
const type = ref("");

// 打开 新增、修改
const openCreateAndEdit = () => {
    type.value = "create";
    router.push({
        path: "/layout/configureDatabase/confCustomerInfoAdd",
    });
};

// 更新行
const updateCustomerInfoFunc = async (row) => {
    // const res = await findCustomerInfo({ ID: row.ID });
    type.value = "update";
    router.push({
        path: "/layout/configureDatabase/confCustomerInfoAdd",
        query: {
            id: row.ID,
        },
    });
};

// 删除行
const deleteCustomerInfoFunc = async (row) => {
    const res = await deleteCustomerInfo({ ID: row.ID });
    if (res.code === 0) {
        ElMessage({
            type: "success",
            message: "删除成功",
        });
        if (tableData.value.length === 1 && pages.value.page > 1) {
            pages.value.page--;
        }
        getTableData();
    }
};

// 关闭详情弹窗
const closeDetailShow = () => {
    detailShow.value = false;
    formData.value = {
        customerNum: "",
    };
};

// 弹窗确定
const enterDialog = async () => {
    elFormRef.value?.validate(async (valid) => {
        if (!valid) return;
        let res;
        switch (type.value) {
            case "create":
                res = await createCustomerInfo(formData.value);
                break;
            case "update":
                res = await updateCustomerInfo(formData.value);
                break;
            default:
                res = await createCustomerInfo(formData.value);
                break;
        }
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "创建/更改成功",
            });
            closeDialog();
            getTableData();
        }
    });
};
</script>

<style>
</style>
